package com.mls.fivedistrict.controller.portal;


import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.controller.BaseController;
import com.mls.fivedistrict.exception.CustomerException;
import com.mls.fivedistrict.pojo.NewsLikeRecord;
import com.mls.fivedistrict.server.AwardService;
import com.mls.fivedistrict.server.NewsLikeRecordService;
import com.mls.fivedistrict.server.NewsService;
import com.mls.fivedistrict.util.validator.BeanValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Five Team
 * @since 2018-06-07
 */
@RestController
@RequestMapping("/api/app")
public class NewsLikeRecordController extends BaseController {
    @Autowired
    NewsLikeRecordService newsLikeRecordService;
    @Autowired
    AwardService awardService;
    @Autowired
    private NewsService newsService;

    /**
     * 快讯点赞接口
     *
     * @param newsLikeRecord
     * @return
     */
    @Transactional
    @PostMapping("/v1/newsLikeRecord")
    public ServiceResponse addNewsLikeRecord(@RequestBody NewsLikeRecord newsLikeRecord) {
        BeanValidator.check(newsLikeRecord);
        newsLikeRecord.setUserId(getUser().getId());
        Long newsId = newsLikeRecord.getNewsId();
        boolean insert = newsLikeRecordService.addNewsLikeRecord(newsLikeRecord);
        if (!insert) {
            return ServiceResponse.createErrorResponse("新闻点赞失败");
        }
        boolean update = newsService.addLikeCount(newsId);
        if (update) {
            return ServiceResponse.createSuccessResponse("新闻点赞成功!");
        } else {
            return ServiceResponse.createErrorResponse("新闻点赞失败");
        }
    }

    /**
     * 取消点赞接口
     *
     * @param newsId
     * @return
     */
    @Transactional
    @DeleteMapping("/v1/newsLikeRecord/{newsId}")
    public ServiceResponse deleteNewsLikeRecord(@PathVariable Long newsId) {
//        Wrapper wrapper = Condition.create();
//        wrapper.eq("user_id", getUser().getId());
//        wrapper.eq("news_id", newsId);
//        NewsLikeRecord newsLikeRecord = newsLikeRecordService.selectOne(wrapper);
//        Optional.ofNullable(newsLikeRecord).orElseThrow(() -> new CustomerException("查无此条点赞记录"));
//        boolean flag = newsLikeRecordService.deleteById(newsLikeRecord);
//        if (flag) {
//            flag = newsService.cutLikeCount(newsId);
//        }
//        if (flag) {
//            return ServiceResponse.createSuccessResponse("取消点赞成功!");
//        } else {
//            return ServiceResponse.createErrorResponse("取消点赞失败");
//        }
        return null;
    }

}

